import Vue from "vue";
import Vuex from "vuex";
import { sysGetByUserName } from "@/api";
import { routes, router } from "@/router";
import checkPermission from "@/utils/permission";
import { isDev } from "@/configurations";
import Cookies from "js-cookie";
import getters from "./getters";
Vue.use(Vuex);
import { loginOutApi } from "@/utils/loginOut";
const modulesFiles = require.context("./modules", true, /\.js$/);

// you do not need `import app from './modules/app'`
// it will auto require all vuex module from modules file
const modules = modulesFiles.keys().reduce((modules, modulePath) => {
  // set './app.js' => 'app'
  const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/, "$1");
  const value = modulesFiles(modulePath);
  modules[moduleName] = value.default;
  return modules;
}, {});

const store = new Vuex.Store({
  modules,
  getters,
  state: {
    yzyToken: null,
    sidebarOpened: true,
    isLogined: isDev, // 开发环境默认为true
    topoNode: {
      data: []
    },
    isAdmin: Cookies.get("isAdmin")
      ? JSON.parse(Cookies.get("isAdmin"))
      : false,
    historyResId: "",
    userNow: Cookies.get("userNow") ? JSON.parse(Cookies.get("userNow")) : {},
    user: {
      username: Cookies.get("userNow")
        ? JSON.parse(Cookies.get("userNow")).userName
        : "",
      imageUri: "",
      role: Cookies.get("userNow")
        ? JSON.parse(Cookies.get("userNow")).role
        : {},
      permissions: ["edit", "remove", "add"],
      menuList: localStorage.getItem("sysMenuList_xinxifabu")
        ? JSON.parse(localStorage.getItem("sysMenuList_xinxifabu"))
        : []
    },
    companyId: Cookies.get("userNow")
      ? JSON.parse(Cookies.get("userNow")).companyId
      : "",
    companyList: [],
    userCompanyList: [],
    layerControl: {
      tianditu: true,
      gzKml: true,
      model: true
    },
    mapControl: {
      height: 0, //地面高度
      center: "" //中心点
    },
    warningList: [],
    paiTotal: 0,
    tousuTotal: 0,
    yjgjTotal: 0,
    yjgjList: [], //预警超时
    warningHidden: localStorage.getItem("warningHidden")
      ? localStorage.getItem("warningHidden")
      : "1"
  },
  getters: {
    /**
     * @description 返回布局视图关系对象，key为布局路径
     */
    sidebarMap() {
      // if (isDev) return routes;

      const result = {};
      router.options.routes.forEach(route => {
        if (!route?.meta?.show) return;
        let newRoute = { ...route };
        if (newRoute.children) {
          // 只加入有权限的路由,404等页面会在这一步被筛掉而不显示
          newRoute.children = newRoute.children.filter(
            child => child?.meta?.show && checkPermission(child.path).length > 0
          );
        }
        if (!newRoute.children.length) return; // 没有子路由的布局不显示
        result[newRoute.path] = newRoute;
      });
      return result;
    },
    /**
     * @description 管理端侧边栏的按钮 通过isAdmin 判断
     */
    sidebarItems() {
      const result = [];
      //   if (isDev) return routes;
      routes.forEach(route => {
        if (!route?.meta?.show) return;
        let newRoute = { ...route };
        if (newRoute.children) {
          // 只加入有权限的路由,404等页面会在这一步被筛掉而不显示
          newRoute.children = newRoute.children.filter(
            child =>
              Number(child.isAdmin) &&
              child?.meta?.show &&
              checkPermission(child.path).length > 0
          );
        }
        if (!newRoute.children?.length) return; // 没有子路由的布局不显示
        result.push(newRoute);
      });
      return result;
    }
  },
  mutations: {
    updatePaiTotal(state, siteInfo) {
      state.paiTotal = siteInfo;
    },
    updateTousuTotal(state, siteInfo) {
      state.tousuTotal = siteInfo;
    },
    updateYjgjTotal(state, siteInfo) {
      state.yjgjTotal = siteInfo;
    },
    updateYjgjList(state, siteInfo) {
      state.yjgjList = siteInfo;
    },
    updateLogined(state, siteInfo) {
      Cookies.set("logined_xinxifabu", siteInfo, {
        expires: 7 //缓存七天
      });
      state.loginStatus = siteInfo;
    },
    updateSysMenuList(state, siteInfo) {
      localStorage.setItem("sysMenuList_xinxifabu", siteInfo);
      state.menuList = siteInfo;
    },
    updateCompanyList(state, siteInfo) {
      state.companyList = siteInfo;
    },
    updateUserCompanyList(state, siteInfo) {
      state.userCompanyList = siteInfo;
    }
  },
  actions: {
    logout() {
      Cookies.set("logined_xinxifabu", "");
      Cookies.set("userNow", "");
      Cookies.remove("cookie_username");
      Cookies.remove("JSESSIONID");
      Cookies.remove("Token");
      Cookies.set("JSESSIONID", "");
      localStorage.removeItem("sysMenuList_xinxifabu", "");
      loginOutApi(); //清除api
    },
    layerControlModel(control) {
      store.state.layerControl.model = control;
    },
    async initUser() {
      let { data } = await sysGetByUserName({
        userName: store.state.user.username
      });
      let lastData = JSON.parse(Cookies.get("userNow"));
      lastData.groupId = data.groupId;
      lastData.topoId = data.topoId;
      Cookies.set("userNow", JSON.stringify(lastData), {
        expires: 7
      });
    }
  }
});

export default store;
